<?php
namespace app\client\controller;
use app\common\lib\Redis;

class Index extends Base {
    public function __construct() {
        parent::__construct();
    }
    
    public function nearDevice() {
        /* if($this->noLogin()) {
            return $this->noLoginReturn();
        } */
        
        $params = request()->get();
        $lng = isset($params['longitude']) ? floatval($params['longitude']) : 114.085947;
        $lat = isset($params['latitude']) ? floatval($params['latitude']) : 22.547;
        $deviceType = isset($params['deviceType']) ? intval($params['deviceType']) : 1;

        unset($params);
        
        $deviceList = [];
        
        $redis = new Redis();
        $geos = $redis->handler()->geoRadius('near_device_' . $deviceType, $lng, $lat, 3000 ,'m' , ['ASC']);
        $redis->close();
        if($geos){
            $deviceIds = [];
            foreach($geos as $deviceId){
                array_push($deviceIds, intval($deviceId));
            }
            
            $deviceList = model('Device')->findAll(['device_id' => $deviceIds], ['device_name', 'device_no', 'port_number', 'charge_port', 'district', 'heart_time', 'signal', 'address', 'longitude', 'latitude']);
            if(!empty($deviceList)) {
                $time = time();
                foreach ($deviceList as &$device) {
                    $device['online'] = $device['heart_time'] > ($time - 300) ? true : false;
                    if($device['online'] == false) {
                        $device['signal'] = 0;
                    }
                }
            }
        }
        
        return successResult(['list' => $deviceList]);
    }
}